package com.miguo.plugins.share;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.miguo.app.AppConfig;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXMusicObject;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;

/**
 * File Names: ShareWXUtils
 * Describe:
 * User: LinXiaoZhi(87100854@qq.com)
 * Date: 2015-10-26
 * Time: 14:19
 */
public class ShareWXUtils {

    public static final int SHARE_DISPOSETYPE_WEBPAGE = 1;
    public static final int SHARE_DISPOSETYPE_TEXT = 2;
    public static final int SHARE_DISPOSETYPE_IMAGE = 3;
    public static final int SHARE_DISPOSETYPE_APP = 4;
    public static final int SHARE_DISPOSETYPE_MUSIC1 = 5;
    public static final int SHARE_DISPOSETYPE_MUSIC2 = 6;
    public static final int SHARE_DISPOSETYPE_OTHER = 7;

    public static IWXAPI createWXAPI(Activity activity) {
        return WXAPIFactory.createWXAPI(activity, AppConfig.SHARE.WX_APP_ID, false);
    }

    public static IWXAPI register(Activity activity) {
        IWXAPI wxApi = WXAPIFactory.createWXAPI(activity, AppConfig.SHARE.WX_APP_ID);
        wxApi.registerApp(AppConfig.SHARE.WX_APP_ID);
        return wxApi;
    }

    public static void disposeType(IWXAPI wxApi, JSONObject json) {
        switch (json.optInt("type")) {
            case SHARE_DISPOSETYPE_WEBPAGE:
                //网页类型
                sendWebPage(wxApi, json.optString("title"), json.optString("desc"), json.optString("image_url"), json.optString("url"), json.optInt("scene"));
                break;
            case SHARE_DISPOSETYPE_TEXT:
                //文本类型
                sendText(wxApi, json.optString("title"), json.optInt("scene"));
                break;
            case SHARE_DISPOSETYPE_IMAGE:
                //发送图片
                sendImage(wxApi, json.optString("image_url"), json.optString("url"), json.optInt("scene"));
                break;
            case SHARE_DISPOSETYPE_APP:
                //APP类型
                sendApp(wxApi, json.optString("title"), json.optString("desc"), json.optString("image_url"));
                break;
            case SHARE_DISPOSETYPE_MUSIC1:
                //音乐类型--音乐播放地址
                sendMusic(wxApi, json.optString("title"), json.optString("desc"), json.optString("image_url"), json.optString("music_url"), json.optInt("scene"));
                break;
            case SHARE_DISPOSETYPE_MUSIC2:
                //音乐类型--音乐URL
                sendMusicLowBand(wxApi, json.optString("title"), json.optString("desc"), json.optString("image_url"), json.optString("music_low_band_url"), json.optInt("scene"));
                break;
            default:
                sendText(wxApi, json.optString("title"), json.optInt("scene"));
        }
    }


    /**
     * 网页类型
     *
     * @param wxApi
     * @param title     标题
     * @param desc      摘要
     * @param image_url 图片地址
     * @param url       点击URL
     * @param scene     发送类型 0:好友 1:朋友圈
     */
    public static void sendWebPage(final IWXAPI wxApi, final String title, final String desc, final String image_url, final String url, final int scene) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = url;
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = title;
                msg.description = desc;

                try {
                    Bitmap bmp = BitmapFactory.decodeStream(new URL(image_url).openStream());
                    Bitmap ImageBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
                    bmp.recycle();
                    msg.setThumbImage(ImageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                req.scene = scene == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
                wxApi.sendReq(req);
            }
        }).start();
    }


    /**
     * 文本类型
     *
     * @param wxApi
     * @param title 文本信息
     * @param scene 发送类型 0:好友 1:朋友圈
     */
    public static void sendText(IWXAPI wxApi, String title, int scene) {
        // 初始化一个WXTextObject对象
        WXTextObject textObj = new WXTextObject();
        textObj.text = title;
        // 用WXTextObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = textObj;
        // 发送文本类型的消息时，title字段不起作用
        // msg.title = "title";
        msg.description = title;

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求
        req.message = msg;
        req.scene = scene == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        wxApi.sendReq(req);
    }

    /**
     * 发送图片
     *
     * @param wxApi
     * @param image_url 图片URL 限制32K以下
     * @param url       链接地址
     * @param scene     发送类型 0:好友 1:朋友圈
     */
    public static void sendImage(final IWXAPI wxApi, final String image_url, final String url, final int scene) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WXImageObject imgObj = new WXImageObject();
                imgObj.imageUrl = url;

                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = imgObj;

                try {
                    Bitmap ImageBitmap = BitmapFactory.decodeStream(new URL(image_url).openStream());
                    msg.setThumbImage(ImageBitmap);
                    ImageBitmap.recycle();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("image");
                req.message = msg;
                req.scene = scene == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
                wxApi.sendReq(req);
            }
        }).start();
    }

    /**
     * APP类型
     *
     * @param wxApi
     * @param title     标题
     * @param desc      摘要
     * @param image_url 图片URL
     */
    public static void sendApp(final IWXAPI wxApi, final String title, final String desc, final String image_url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WXAppExtendObject appdata = new WXAppExtendObject();
                appdata.extInfo = "MeGuo";
                WXMediaMessage msg = new WXMediaMessage();
                msg.title = title;
                msg.description = desc;
                msg.mediaObject = appdata;

                try {
                    Bitmap bmp = BitmapFactory.decodeStream(new URL(image_url).openStream());
                    Bitmap ImageBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
                    bmp.recycle();
                    msg.setThumbImage(ImageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("appdata");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;
                wxApi.sendReq(req);
            }
        }).start();
    }


    /**
     * 音乐类型--音乐播放地址
     * (如:http://www.meguo.com/mp3.mp3)
     *
     * @param wxApi
     * @param title     标题
     * @param desc      摘要
     * @param image_url 图片URL
     * @param music_url 播放URL
     * @param scene     发送类型 0:好友 1:朋友圈
     */
    public static void sendMusic(final IWXAPI wxApi, final String title, final String desc, final String image_url, final String music_url, final int scene) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WXMusicObject music = new WXMusicObject();
                music.musicUrl = music_url;
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = music;
                msg.title = title;
                msg.description = desc;

                try {
                    Bitmap bmp = BitmapFactory.decodeStream(new URL(image_url).openStream());
                    Bitmap ImageBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
                    bmp.recycle();
                    msg.setThumbImage(ImageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("music");
                req.message = msg;
                req.scene = scene == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
                wxApi.sendReq(req);
            }
        }).start();
    }


    /**
     * 音乐类型--音乐URL
     * (如:http://www.meguo.com/mp3)
     *
     * @param wxApi
     * @param title              标题
     * @param desc               摘要
     * @param image_url          图片URL
     * @param music_low_band_url 音乐URL
     * @param scene              发送类型 0:好友 1:朋友圈
     */
    public static void sendMusicLowBand(final IWXAPI wxApi, final String title, final String desc, final String image_url, final String music_low_band_url, final int scene) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WXMusicObject music = new WXMusicObject();
                music.musicLowBandUrl = music_low_band_url;

                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = music;
                msg.title = title;
                msg.description = desc;
                try {
                    Bitmap bmp = BitmapFactory.decodeStream(new URL(image_url).openStream());
                    Bitmap ImageBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
                    bmp.recycle();
                    msg.setThumbImage(ImageBitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("music");
                req.message = msg;
                req.scene = scene == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
                wxApi.sendReq(req);
            }
        }).start();
    }

/*
    private static String imageUrl;

    private static Bitmap ImageBitmap;

    private static Runnable downloadImageRun = new Runnable() {
        @Override
        public void run() {
            try {
//                Bitmap bmp = BitmapFactory.decodeStream(new URL(imageUrl).openStream());
//                ImageBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
//                bmp.recycle();
//                ImageSize size = new ImageSize(150,150);
//                ImageBitmap = ImageLoader.getInstance().loadImageSync(imageUrl,size);
                Bitmap bmp = BitmapFactory.decodeStream(new URL(imageUrl).openStream());
                ImageBitmap = Bitmap.createScaledBitmap(bmp, 150, 150, true);
                bmp.recycle();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    */


    private static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static String buildTransaction(String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
